<template>
  <ContentWrap v-loading="formLoading">
    <ObtainGuestForm
      v-model:formData="formData"
      :is-detail="isDetail"
      ref="obtainGuestFormRef"
    />
  </ContentWrap>
  <el-col>
    <el-tabs>
      <el-tab-pane label="获客附件">
        <ContentWrap :loading="formLoading">
          <el-form-item label="附件" prop="attachmentUrls">
            <UploadFile
              :is-show-tip="false"
              v-model="formData.attachmentUrls"
              :limit="20"
              :disabled="isDetail"/>
          </el-form-item>
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="操作日志" v-if="isDetail">
        <OperateLogV2 :log-list="logList" />
      </el-tab-pane>
    </el-tabs>
  </el-col>

  <el-form>
    <el-form-item style="margin: 0 auto; display: table;">
      <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
        保存
      </el-button>
      <el-button @click="close">返回</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { BizTypeEnum } from '@/api/crm/permission'
import { getOperateLogPage } from '@/api/crm/operateLog'
import type { ObtainGuestVO } from '@/api/crm/obtainguest'
import { ObtainGuestApi } from '@/api/crm/obtainguest'
import { useUserStore } from '@/store/modules/user'
import type { FormInstance } from 'element-plus'
import ObtainGuestForm from '../components/ObtainGuestForm.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const isDetail = ref(false)
const formLoading = ref(false) // 表单的加载中
const formData = ref<ObtainGuestVO>({
  id: undefined,
  obtainGuestNo: undefined,
  clientType: undefined,
  clientName: undefined,
  taxNumber: undefined,
  clientPhone: undefined,
  businessManagerId: undefined,
  businessManagerName: undefined,
  businessManagerPhone: undefined,
  payType: undefined,
  sellType: undefined,
  contractType: undefined,
  productType: undefined,
  clientAreaId: undefined,
  clientDetailAddress: undefined,
  remark: undefined,
  belongArea: undefined,
  attachmentUrls: [],
  clientAreaName: undefined,
})

// 获取子组件的引用
const obtainGuestFormRef = ref<{ formRef: FormInstance }>()

/** 获取操作日志 */
const logList = ref([]) // 操作日志列表
const getOperateLog = async () => {
  const data = await getOperateLogPage({
    bizType: BizTypeEnum.CRM_OBTAIN_GUEST,
    bizId: params.id as unknown as number
  })
  logList.value = data.list
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件
const submitForm = async () => {
  // 通过子组件引用获取表单实例并验证
  if (!obtainGuestFormRef.value?.formRef) return
  const valid = await obtainGuestFormRef.value.formRef.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ObtainGuestVO
    const id = params.id as unknown as number
    if (!id) {
      await ObtainGuestApi.createObtainGuest(data)
      message.success(t('common.createSuccess'))
    } else {
      await ObtainGuestApi.updateObtainGuest(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
  close()
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ObtainGuest' })
}

/** 获得详情 */
const getDetail = async () => {
  if ('CrmObtainGuestDetail' === name) {
    isDetail.value = true
  }
  const id = params.id as unknown as number
  if (id) {
    try {
      formLoading.value = true
      formData.value = await ObtainGuestApi.getObtainGuest(id)
      await getOperateLog()
    } finally {
      formLoading.value = false
    }
  } else {
    // 默认新建时选中自己
    formData.value.businessManagerId = useUserStore().getUser.id
  }
}

onMounted(async () => {
  await getDetail()
})
</script>
